<template>
    <el-dialog :width="dialog.width || '40%'"
               :visible="dialog.visible"
               :modal-append-to-body="false"
               :close-on-click-modal="false"
               @close="close">
        <div slot="title" class="text-center">
            <span class="font-s20">
                <icon name="setting"></icon>
                账户设置
            </span>
        </div>
        <el-form ref="modelForm"
                 size="medium"
                 label-position="top"
                 :model="model"
                 :rules="rules"
                 :inline-message="true"
                 :status-icon="true"
                 @submit.native.prevent>
            <el-scrollbar class="r-custom-scrollbar custom-scroll-height">
                <div class="pl-20 pr-20">
                    <el-form-item class="el-form-item--upload">
                        <div slot="label">
                            <div class="r-flex">
                                <div class="mr-20">头像</div>
                                <div class="r-flex__item">
                                    <span class="text-warning"><icon name="tips"></icon> 仅支持JPG、PNG格式，文件小于2M(方形图)</span>
                                </div>
                            </div>
                        </div>
                        <el-upload ref="upload"
                                   class="upload"
                                   action=""
                                   accept=".jpg, .png, .jpeg"
                                   drag
                                   :show-file-list="false"
                                   :http-request="chooseImage">
                            <div class="upload-image">
                                <el-avatar :size="120"
                                           :src="user_info.avatar"
                                           icon="el-icon-user-solid font-s40"></el-avatar>
                                <div class="upload-image__progress">
                                    <el-progress v-show="upload.progress > 0 && !upload.finish" :text-inside="true"
                                                 :stroke-width="16"
                                                 :percentage="upload.progress"
                                                 status="success"></el-progress>
                                </div>
                            </div>
                        </el-upload>
                    </el-form-item>

                    <el-form-item label="密码" prop="old_password">
                        <el-input type="text"
                                  placeholder="密码"
                                  maxlength="16"
                                  show-password
                                  v-model="model.old_password"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="password">
                        <el-input type="text"
                                  placeholder="密码"
                                  maxlength="16"
                                  show-password
                                  v-model="model.password"></el-input>
                    </el-form-item>

                    <el-form-item label="确认密码" prop="password_confirmation">
                        <el-input type="text"
                                  placeholder="确认密码"
                                  maxlength="16"
                                  show-password
                                  v-model="model.password_confirmation"></el-input>
                    </el-form-item>

                    <el-form-item label="手机号码" prop="mobile">
                        <el-input placeholder="手机号码"
                                  maxlength="11"
                                  v-model="model.mobile"></el-input>
                    </el-form-item>

                    <el-form-item label="邮箱" prop="email">
                        <el-input type="text"
                                  placeholder="邮箱"
                                  maxlength="50"
                                  v-model="model.email"></el-input>
                    </el-form-item>

                </div>
            </el-scrollbar>
            <div class="mt-20 text-right">
                <el-button type="text" size="medium" @click="close">取消</el-button>
                <el-button type="primary"
                           size="medium"
                           icon="moe-icon moe-icon-save"
                           :loading="saveLoading"
                           native-type="submit"
                           @click="submitForm('modelForm')">确定
                </el-button>
            </div>
        </el-form>
    </el-dialog>
</template>

<script lang="ts">
import { Component, Prop, Emit, Vue } from 'vue-property-decorator'
import { namespace } from 'vuex-class'

import { errorMessage, successMessage } from '@/utils'
import { validateMobile } from '@/utils/rules'

import * as http from '@/http/cms'

const cmsModule = namespace('cms')
const adminUserModule = namespace('cms/adminUser')

@Component
export default class Edit extends Vue {
  @Prop({ type: Boolean, default: false }) visible!: boolean
  @Prop({ type: Object, default: {} }) dialog!: any

  // Vuex
  @cmsModule.State user_info!: any
  @cmsModule.Mutation setUserInfo!: (data: any) => void
  @adminUserModule.State adminUser!: any
  @adminUserModule.Action update!: (payload: any) => Promise<any>
  @adminUserModule.Action setAvatar!: (payload: any) => Promise<any>
  @adminUserModule.Action setting!: (payload: any) => Promise<any>


  // form模型
  public model: any = {
    old_password: '',
    password: '',
    password_confirmation: '',
    mobile: '',
    email: ''
  }

  /**
   * validator 确认密码验证
   *
   * @return {any}
   */
  private confirmPassword: any = (rule: any, value: string, callback: any) => {
    if (value === '') {
      callback('请重新输入密码')
    } else if (value !== this.model.password) {
      callback('两次密码输入不一致')
    } else {
      callback()
    }
  }

  // 验证规则
  private rules: any = {
    // old_password: [],
    // password: [
    //   { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
    // ],
    // password_confirmation: [
    //   { validator: this.confirmPassword, trigger: 'blur' }
    // ],
    mobile: [
      { required: true, message: '请填写手机号码', trigger: 'blur' },
      { validator: validateMobile, trigger: 'blur' }
    ],
    email: [
      { required: true, message: '请填写邮箱', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ]
  }


  // 上传
  private upload: any = {
    action: '',
    progress: 0,
    finish: true
  }

  private saveLoading: boolean = false // 保存加载状态

  /*----- 钩子 -----*/
  private created() {
    this.model.mobile = this.user_info.mobile
    this.model.email = this.user_info.email
  }

  /**
   * 选择图片
   *
   * @param {object} params
   */
  private chooseImage(params: any): void {
    const that = this,
      file = params.file,
      fileType = file.type,
      isImage = fileType.indexOf('image') !== -1

    if (!isImage) {
      errorMessage('仅支持图片文件')
      return
    }

    that.upload.progress = 0
    that.upload.finish = false
    that.handleUploadFile(file).then((res) => {
      that.upload.finish = true
      if (res.status === 200) {
        that.setAvatar({ params: { avatar: res.data.file_path } }).then((res) => {
          res.status === 200 ? successMessage(res.message) : errorMessage(res.message)
        })
      }
    }).catch((err) => {
      that.upload.finish = true
    })
  }

  /**
   * 上传图片
   *
   * @param {any} file 选中的文件
   */
  protected handleUploadFile(file: any): Promise<any> {
    const formData = new FormData()
    formData.append('upload_file', file)
    return http.uploadFile(formData, {
      onUploadProgress: (event: any) => {
        this.upload.progress = parseInt((event.loaded / event.total * 100).toFixed(0))
      }
    })
  }

  /**
   * 提交表单
   *
   * @param name
   */
  private submitForm(name: string): void | boolean {
    (this.$refs[name] as any).validate((valid: boolean) => {
      if (valid) {
        this.saveLoading = true
        this.setting({ id: this.user_info.id, params: this.model }).then((res) => {
          this.saveLoading = false
          if (res.status !== 200) {
            errorMessage(res.message)
            return false
          }


          // 更新 admin 用户信息
          this.setUserInfo(res.data)

          successMessage(res.message)
          this.close()
        }).catch((err) => {
          this.saveLoading = false
        })
      }
    })
  }

  /**
   * 重置表单
   *
   * @param name
   */
  private resetForm(name: string): void {
    (this.$refs[name] as any).resetFields()
  }

  @Emit()
  close(): void {
    this.resetForm('modelForm')
    this.saveLoading = false
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/element/element-variables";

.custom-scroll-height {
    height: 400px;
}

.el-form-item--upload {
    ::v-deep .el-form-item__content {
        font-size: 0;
        line-height: 1;
    }

    .upload {
        position: relative;
        text-align: center;

        &-image {
            position: relative;
            overflow: hidden;

            &__progress {
                position: absolute;
                top: 0;
                right: 0;
                left: 0;
                opacity: .9;
            }
        }

        ::v-deep .el-upload {
            cursor: pointer;
            position: relative;
            overflow: hidden;
            width: 100% !important;
            height: 100% !important;

            &:hover {
                border-color: $--color-primary;
            }

            &-dragger {
                padding: 20px;
                width: 100% !important;
                height: 100% !important;
                border-width: 2px;

                &.is-dragover {
                    background: rgba($--color-primary, .05);
                }
            }
        }
    }
}
</style>
